<!--
 * @Date: 2023-09-01 10:59:23
 * @LastEditTime: 2023-10-09 16:44:27
 * 介绍:
-->
<route lang="json">
{
  "meta": {
    "title": "t('ren-wu-bian-ji')"
  }
}
</route>
<script lang="ts" setup>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import type {
  IToolbarConfig,
  IDomEditor,
  IEditorConfig,
} from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css";
import { showNavbar, hidNavbar } from "@@/layout/navbar";
import { imageCompress } from "@@/utils/tools/file";
import { uploadImages } from "@@/api/module/upload";
import { notify, toast } from "@@/hooks/vantHooks";
import { apiAddTask, ApiAddTask } from "@@/api/wk/index";
import { CinputImage } from "@@/components/common/CinputImages/index";
import useTabPageStore from "@@/store/useTabPageStore";
import useBalanceStore from "@@/store/useBalanceStore";
import { chain } from "mathjs";
import pay from "./components/pay.vue";
import { remToPx } from "@@/utils/tools/css";
import router from "@@/router";
import { isNonNullStr } from "@@/utils/tools/is";
import { computeAddTaskPlayInfo } from "./components/mix";

const { t } = useI18n();
const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    "headerSelect",
    "bold",
    "underline",
    "italic",
    "through",

    "indent",
    "delIndent",
    "justifyLeft",
    "justifyRight",
    "justifyCenter",
    "justifyJustify",
    "|",
    "numberedList",
    // "uploadImage",
    "|",
    "undo",
    "redo",
    "fullScreen",
  ],
};
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef<IDomEditor>();

const editorConfig: Partial<IEditorConfig> = {
  placeholder: t("qing-tian-xie-gai-zi-duan"),
  autoFocus: false,
};

// interface InsertFnType {
//   (url: string, alt: string, href: string): void;
// }
// editorConfig.MENU_CONF = {
//   ...editorConfig.MENU_CONF,
//   uploadImage: {
//     fieldName: "file",
//     maxNumberOfFiles: 9,
//     maxFileSize: 1024 * 1024 * 99,
//     async customUpload(file: File, insertFn: InsertFnType) {
//       notify.primary(t("zhen-zai-ya-suo-tu-pian"), {
//         duration: 0,
//       });
//       if (file.size > UPLOAD_FILE_MAX)
//         file = await imageCompress(file, UPLOAD_FILE_MAX);
//       const formData = new FormData();
//       formData.append("file", file);
//       notify.primary(t("zhen-zai-shang-chuan-tu-pian"), {
//         duration: 0,
//       });
//       const res = await uploadImage(formData);
//       if (res.errno !== 0) {
//         notify.error(t("shang-chuan-shi-bai"));
//         return;
//       }
//       notify.success(t("shang-chuan-cheng-gong"));
//       insertFn(res.data.urls[0], "image", res.data.paths[0]);
//     },
//   },
// };
// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

function editorFull() {
  if (!editorRef.value) return;
  editorRef.value.fullScreen();
  editorRef.value.focus();
}

// 编辑器回调函数
function handleCreated(editor: IDomEditor) {
  editorRef.value = editor; // 记录 editor 实例，重要！
}
function handleChange(editor: IDomEditor) {
  // console.log("change:", editor.getHtml());
}
function handleFocus(editor: IDomEditor) {
  hidNavbar();
}
function handleBlur(editor: IDomEditor) {
  showNavbar();
}

const form = reactive<ApiAddTask.Req>({
  capital: "",
  commission: "",
  details: "",
  images: "",
  introduction: "",
  order_limit_time: "",
  txid: "",
  watchword: "",
});
let images: CinputImage[] = [];

const tabPageStore = useTabPageStore();
const { homeData } = storeToRefs(tabPageStore);
const balanceStore = useBalanceStore();
const WKC = computed(() => balanceStore.getCoinByCode("WKC"));

const payRef = ref<InstanceType<typeof pay>>();

const btnLoading = reactive({
  submit: false,
});

const addTaskPlayInfo = computed(() => computeAddTaskPlayInfo(form));

async function openPay() {
  btnLoading.submit = true;
  const [apiRes] = await Promise.all([
    tabPageStore.getHomeData(),
    balanceStore.findBalance(WKC.value),
  ]);
  btnLoading.submit = false;
  if (!apiRes) return;

  btnLoading.submit = true;
  await payRef.value?.open(addTaskPlayInfo.value);
  btnLoading.submit = false;
}

function onSubmit() {
  if (editorRef.value?.isEmpty()) return;
  openPay();
}
async function addTask(txid: string) {
  form.txid = txid;
  form.images = await uploadImages(images);
  await apiAddTask(form);
  router.back();
}

function commissionValidator(v: string) {
  const val = Number(v);
  /**本金 */
  const capital = Number(form.capital);
  /**比率 */
  const ratio = Number(homeData.value?.task_setting.task_commission_limit);
  const mini = chain(ratio).multiply(0.01).multiply(capital).done();
  if (val < mini) {
    return `${t("ren-wu-yong-jin-bu-de-di-yu-ben-jin")} ${ratio}%`;
  }
  if (!(val < Number(form.capital))) return t("yongJingBiXuXiaoYuBengJing");
  return true;
}
function watchwordValidator(v: string = "") {
  v = v.toString();
  if (!v || /^\d{15}$/.test(v)) return true;
  return t("bi-xu-15-wei-zheng-shu");
}
</script>
<template>
  <CpageView>
    <pay @play-success="addTask" ref="payRef" />
    <van-form @submit="onSubmit">
      <div class="auto-MT-md">
        <Ccard class="PT-xs PB-xs" border-style="none">
          <Rinput
            :label="$t('ren-wu-jian-cheng')"
            v-model="form.introduction"
            :border-mode="'bottom'"
            required
            :rules="[
              {
                validator: isNonNullStr,
                message: $t('qing-tian-xie-gai-zi-duan'),
              },
            ]"
            maxlength="30"
          />
          <Rinput
            :label="$t('ren-wu-ben-jin-0')"
            v-model="form.capital"
            :border-mode="'bottom'"
            required
            :rules="[
              { required: true, message: $t('qing-tian-xie-gai-zi-duan') },
            ]"
            type="number"
          >
            <template #right-icon>
              <span>USDT</span>
            </template>
          </Rinput>
          <Rinput
            :label="$t('kou-ling-she-zhi')"
            :rules="[
              {
                validator: watchwordValidator,
              },
            ]"
            v-model="form.watchword"
            :border-mode="'none'"
            :type="'digit'"
            maxlength="15"
          >
            <template #button>
              <Rpopover
                :offset="[remToPx(30), remToPx(14)]"
                :placement="'top-end'"
              >
                <template #reference>
                  <Cicon size="24rem" name="icon-help" />
                </template>
                <div class="tips_content">
                  {{
                    $t(
                      "ru-guo-shu-ru-kou-ling-bie-ren-xu-yao-tong-guo-kou-ling-cai-neng-kan-dao-ren-wu"
                    )
                  }}
                </div>
              </Rpopover>
            </template>
          </Rinput>
        </Ccard>
        <Ccard class="auto-MT-md" border-style="none">
          <Rinput
            :label="$t('ren-wu-yong-jin-0')"
            v-model="form.commission"
            required
            :rules="[
              { required: true, message: $t('qing-tian-xie-gai-zi-duan') },
              {
                validator: commissionValidator,
              },
            ]"
            type="number"
          >
            <template #right-icon>
              <span>USDT</span>
            </template>
          </Rinput>
        </Ccard>
        <div v-if="addTaskPlayInfo.servePrice" class="T-S-sm C-M1">
          {{ $t("ping-tai-fu-wu-fei") }}
          {{ addTaskPlayInfo.servePrice }}USDT
        </div>
        <Ccard border-style="none">
          <Rinput
            :label="$t('ren-wu-qi-xian')"
            v-model="form.order_limit_time"
            :type="'digit'"
            required
            :rules="[
              { required: true, message: $t('qing-tian-xie-gai-zi-duan') },
              {validator:(v:string)=>Number(v) >= 1,message:$t('bu-xiao-yu-1-de-zheng-shu')},
            ]"
          >
            <template #right-icon>
              <span>/ H</span>
            </template>
          </Rinput>
        </Ccard>
        <Ccard border-style="none">
          <Rinput :label="$t('ren-wu-xiang-qing-0')" required>
            <template #input>
              <div>
                <Toolbar
                  class="Toolbar"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="'default'"
                  style="border-bottom: 1px solid #ccc"
                />
                <Editor
                  class="Editor"
                  :defaultConfig="editorConfig"
                  :mode="'default'"
                  v-model="form.details"
                  @onCreated="handleCreated"
                  @onChange="handleChange"
                  @onFocus="handleFocus"
                  @onBlur="handleBlur"
                />
              </div>
            </template>
            <template #button>
              <Cicon name="icon-quanping" @click="editorFull()" />
            </template>
          </Rinput>
        </Ccard>

        <CinputImages @change="(e) => (images = e)" :max-length="3" />
        <Rbutton
          :loading="btnLoading.submit"
          native-type="submit"
          class="MT-lg"
          :size="'large'"
          bg="var(--C-LG1)" borderStyle="none"
        >
          {{ $t("ti-jiao") }}
        </Rbutton>
      </div>
    </van-form>
  </CpageView>
</template>
<style lang="scss" scoped>
.tips_content {
  max-width: 50vw;
  font-size: var(--T-S-sm);
  padding: var(--gap-xs);
}
.Toolbar {
  visibility: hidden;
  height: 0;
}
.Editor {
  width: 100%;
  flex: 1;
}
.w-e-full-screen-container {
  background-color: var(--C-B1);
  z-index: 100;
  .Toolbar {
    visibility: visible;
    height: auto;
  }
}
</style>
